package com.linh.location;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class PlaceFindingTask extends AsyncTask<HttpUriRequest, Void, String> {

	public static final String PLACE_FINDING_RESULT = "placeResult";

	private Context context;

	private HttpClient httpClient;

	private String action;

	private LocationParser locationParser;

	public PlaceFindingTask(Context context, String action) {
		super();
		this.context = context;
		this.action = action;
		this.httpClient = new DefaultHttpClient();
		this.locationParser = new LocationParser();
	}

	@Override
	protected String doInBackground(HttpUriRequest... request) {
		try {
			HttpResponse httpResponse = httpClient.execute(request[0]);
			String result = new BasicResponseHandler()
					.handleResponse(httpResponse);
			return result;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i(getClass().getName(), result);
		ArrayList<BusStop> busStops = new ArrayList<BusStop>(locationParser.parse(
				result).values());
		Intent intent = new Intent(action);
		intent.putExtra(PLACE_FINDING_RESULT, busStops);
		context.sendBroadcast(intent);
	}

}
